package com.jxtc.enterprise.hr.service;

import cn.hutool.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jxtc.enterprise.common.entity.Company;
import com.jxtc.enterprise.common.exception.LoginFailureException;
import com.jxtc.enterprise.common.mapper.CompanyMapper;
import com.jxtc.enterprise.hr.dto.HrLoginFormDTO;
import com.jxtc.enterprise.hr.vo.HrLoginSuccessVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Optional;

@Service
@RequiredArgsConstructor
@Slf4j
public class HrLoginService {

    private final CompanyMapper companyMapper;
    private final BCryptPasswordEncoder passwordEncoder;

    /**
     * 登录过期时间，单位：毫秒
     */
    public final long LOGIN_EXPIRE_TIME = 1000L * 60 * 60 * 24 * 30;
    /**
     * JWT 加密密钥
     */
    public final String HR_LOGIN_JWT_KEY = "aiyi2SZFDR0P0i6HRODlbhd5wqmhE5HrRhYPePXAmmBRCbluN9lh1xiZJSxtMHUWnw0_vmd3bK-6DQfVyt87bw";

    public HrLoginSuccessVO login(HrLoginFormDTO dto) {
        QueryWrapper<Company> wrapper = new QueryWrapper<>();
        wrapper.eq("phone_number", dto.getPhoneNumber());
        wrapper.eq("del_flag", 0);
        wrapper.orderByDesc("create_time");

        // 对于可能出现的多条数据，取最新的一条数据
        Optional<Company> companyOptional = companyMapper.selectList(wrapper).stream().findFirst();
        if (!companyOptional.isPresent()) {
            throw new LoginFailureException("账号不存在");
        }

        Company company = companyOptional.get();

        // 验证密码
        // boolean matches = passwordEncoder.matches(dto.getPassword(), company.getPassword()); // 暂时不加密
        boolean matches = company.getPassword().equals(dto.getPassword());

        if (matches) {
            String token = JWT.create()
                    .setPayload("name", company.getHrName())
                    .setPayload("role", "HR")
                    .setPayload("companyId", company.getId())
                    .setExpiresAt(new Date(System.currentTimeMillis() + LOGIN_EXPIRE_TIME))
                    .setKey(HR_LOGIN_JWT_KEY.getBytes())
                    .sign();
            return new HrLoginSuccessVO(company.getHrName(), company.getId(), company.getName(), token);
        }

        throw new LoginFailureException("账号或密码错误");
    }
}
